package com.originskyseed.platform.common.api.util;

import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.common.api.config.QueryUrlConfig;
import com.originskyseed.platform.core.config.bean.ConfigManager;
import com.originskyseed.platform.core.mongodb.api.MongoUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;

public class QueryAppUtil {

	/**
	 * 日志记录表
	 */
	private final static String INTERFACE_SYNCHRO_LOG = "osi_interface_synchro_log";

	/**
	 * 查询青芒接口
	 * 
	 * @param method       请求接口名称
	 * @param type         请求方式 1 get请求，2post请求
	 * @param paramMap//参数
	 * @return
	 */
	public static Map query(String method, int type, TreeMap<String, Object> paramMap) throws Exception {
		Map map = new HashMap();
		String desc = "";
		String url = "";
		String content="";
		QueryUrlConfig queryUrlConfig = ConfigManager.getInstance().parseObject(QueryUrlConfig.class);
		//System.out.println("===queryUrlConfig="+queryUrlConfig);
		switch (method) {
		case "familyInfoUrl":
			desc = "查询家族信息接口";
			url = queryUrlConfig.getFamilyInfoUrl();
			break;
		case "anchorInfoUrl":
			desc = "查询主播信息接口";
			url = queryUrlConfig.getAnchorInfoUrl();
			break;
		case "anchorInfoBatchUrl":
			desc = "批量查询主播信息接口";
			url = queryUrlConfig.getAnchorInfoBatchUrl();
			break;
		case "guildInfoUrl":
			desc = "查询推广公会信息接口";
			url = queryUrlConfig.getGuildInfoUrl();
			break;
		case "anchorViolationInfoUrl":
			desc = "查询主播违规信息接口";
			url = queryUrlConfig.getAnchorViolationInfoUrl();
			break;
		case "anchorLiveStatusUrl":
			desc = "主播禁播/开播接口";
			url = queryUrlConfig.getAnchorLiveStatusUrl();
			break;
		case "anchorRejectUrl":
			desc = "主播剔除家族接口";
			url = queryUrlConfig.getAnchorRejectUrl();
			break;
		case "anchorOnlineUrl":
			desc = "查询主播是否在线接口";
			url = queryUrlConfig.getAnchorOnlineUrl();
			break;
		case "playerChannelUrl":
			desc = "玩家改绑申请接口";
			url = queryUrlConfig.getPlayerChannelUrl();
			break;
		case "playerAwardQueryUrl":
			desc = "玩家奖励申请查询接口";
			url = queryUrlConfig.getPlayerAwardQueryUrl();
			break;
		case "playerAwardSubmitUrl":
			desc = "玩家奖励申请提交接口";
			url = queryUrlConfig.getPlayerAwardSubmitUrl();
			break;
		case "appInfoUrl":
			desc = "查询产品信息接口";
			url = queryUrlConfig.getAppInfoUrl();
			break;
		case "queryAppVersionByAppIdUrl":
			desc = "根据产品id和子渠道id获取最新版本";
			url = queryUrlConfig.getQueryAppVersionByAppIdUrl();
			break;
		case "queryAnchorInfoByAppIdUrl":
			desc = "根据产品id和业务员id查询对应的主播信息接口";
			url = queryUrlConfig.getQueryAnchorInfoByAppIdUrl();
			break;
		case "queryUnionUrl":
			desc = "根据渠道id查询工会接口";
			url = queryUrlConfig.getQueryUnionUrl();
			break;
		case "queryFocusAnchorUrl":
			desc = "关注主播接口";
			url = queryUrlConfig.getQueryFocusAnchorUrl();
			break;
		case "playerOnlineUrl":
			desc = "查询玩家是否在线接口";
			url = queryUrlConfig.getPlayerOnlineUrl();
			break;
		case "invitationLinkUrl":
			desc = "邀请链接接口";
			url = queryUrlConfig.getInvitationLinkUrl();
			break;
		default:
			break;
		}
		// 记录日志
		JSONObject synchroLogJsonObj = new JSONObject();
		String id = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
		synchroLogJsonObj.put("id", id);
		synchroLogJsonObj.put("state", 2);
		synchroLogJsonObj.put("startTime", new Date());
		synchroLogJsonObj.put("desc", desc);
		synchroLogJsonObj.put("name", url);
		synchroLogJsonObj.put("type", 2);
		synchroLogJsonObj.put("createTime", new Date());

		boolean res = false;
		String code = "0";
		String msg = "";
		String data = "";
		int totalNum=0;
		String domainUrl = queryUrlConfig == null ? "" : queryUrlConfig.getDomainUrl();
		if (domainUrl == null || StringUtils.isEmpty(domainUrl)||url==null||StringUtils.isEmpty(url)) {
			code = "7002";
			msg = "域名地址或请求地址为空,请联系管理员";
		} else {
			url = domainUrl + url;
			String timestamp = System.currentTimeMillis() + "";
			String nonce = genReqID();
			String md5Sign="";
			TreeMap paramMap0=new TreeMap();
			if (method.equals("playerChannelUrl")) // 玩家改绑申请接口
			{
				paramMap0.put("timestamp", timestamp);
				paramMap0.put("nonce", nonce);
				md5Sign = getSign(paramMap0, queryUrlConfig.getEncryKey());
			}
			else
			{
				paramMap.put("timestamp", timestamp);
				paramMap.put("nonce", nonce);
				md5Sign = getSign(paramMap, queryUrlConfig.getEncryKey());
				paramMap.put("sign", md5Sign);
			}

			if (type == 1) {
				String tempParam = "";
				for (String key : paramMap.keySet()) {
					if (key != null && StringUtils.isNotEmpty(key)) {
						String value = paramMap.get(key) == null ? "" : paramMap.get(key).toString();
						if (StringUtils.isNotEmpty(tempParam)) {
							tempParam = tempParam + "&" + key + "=" + value;
						} else {
							tempParam = tempParam + key + "=" + value;
						}
					}
				}
				if (tempParam != null && StringUtils.isNotEmpty(tempParam)) {
					url = url + "?" + tempParam;
				}
				content = HttpUtil.doGet(url);
			} else {
				if (method.equals("playerChannelUrl")) {
					url=url+"?timestamp="+timestamp+"&nonce="+nonce+"&sign="+md5Sign;

					JSONObject jsonObject=new JSONObject();
					for (String key : paramMap.keySet()) {
						if (key != null && StringUtils.isNotEmpty(key)) {
							String value = paramMap.get(key) == null ? "" : paramMap.get(key).toString();
							jsonObject.put(key,value);
						}
					}
					content = HttpUtil.doPost(url, jsonObject);
				}
				else
				{
					content = HttpUtil.doPost(url, paramMap);
				}
			}
			if (content != null && StringUtils.isNotEmpty(content)) {
				JSONObject jsonObj = JSON.parseObject(content);
				if (jsonObj != null) {
					if (jsonObj.containsKey("code")) {
						code = jsonObj.getString("code");
						msg = jsonObj.getString("msg");
						data = jsonObj.getString("data");
						if(jsonObj.containsKey("totalNum")) {
							totalNum = jsonObj.getInteger("totalNum");
						}
						// 当返回失败时，需要记录失败的日志记录
						if (!(code != null && StringUtils.isNotEmpty(code) && code.equals("1"))) {

							res = true;
						}
					} else {
						msg = "json对象有误，没有包含状态码";
						res = true;

					}
				} else {
					msg = "转json对象失败";
					res = true;
				}
			} else {
				msg = "返回值为空";
				res = true;
			}
		}
		if (res) {
			System.out.println("==content=="+content+"==url=="+url+"==paramMap=="+paramMap+"==entrykey=="+queryUrlConfig.getEncryKey());
			synchroLogJsonObj.put("endTime", new Date());
			synchroLogJsonObj.put("errorLog", msg);

			MongoUtil.getInstance().insert(synchroLogJsonObj, INTERFACE_SYNCHRO_LOG);
		}
		map.put("code",  Integer.parseInt(code));
		map.put("msg", msg);
		map.put("totalNum", totalNum);
		map.put("data", data);
		return map;
	}

	public static String genReqID() {
		return UUID.randomUUID().toString().replace("-", "").toUpperCase();
	}

	private static String getSign(Map<String, Object> signMap, String encryKey) {
		StringBuilder signSb = new StringBuilder();
		signMap.forEach((key, value) -> {
			if (signSb.length() > 0) {
				signSb.append("&");
			}
			signSb.append(key).append("=").append(urlEncode(value.toString()));
		});

		String mySign =MD5Util.digest(signSb.toString() + encryKey);
		return mySign;
	}

	private static String urlEncode(String value) {
		String encode = value;
		try {
			encode = URLEncoder.encode(value, "UTF-8");
			encode = encode.replaceAll("\\+", "%20");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return encode;
	}


	/**
	 * 查询青芒接口
	 *
	 * @param method       请求接口名称
	 * @param type         请求方式 1 get请求，2post请求
	 * @param paramMap//参数
	 * @return
	 */
	public static Map testQuery(String method, int type, TreeMap<String, Object> paramMap) throws Exception {
		Map map = new HashMap();
		String desc = "";
		String url = "";
		String content="";
		QueryUrlConfig queryUrlConfig = ConfigManager.getInstance().parseObject(QueryUrlConfig.class);
		switch (method) {
			case "familyInfoUrl":
				desc = "查询家族信息接口";
				url = queryUrlConfig.getFamilyInfoUrl();
				break;
			case "anchorInfoUrl":
				desc = "查询主播信息接口";
				url = queryUrlConfig.getAnchorInfoUrl();
				break;
			case "anchorInfoBatchUrl":
				desc = "批量查询主播信息接口";
				//url = queryUrlConfig.getAnchorInfoBatchUrl();
				url="/kingDee/anchor/info/batch";
				break;
			case "guildInfoUrl":
				desc = "查询推广公会信息接口";
				url = queryUrlConfig.getGuildInfoUrl();
				break;
			case "anchorViolationInfoUrl":
				desc = "查询主播违规信息接口";
				//url = queryUrlConfig.getAnchorViolationInfoUrl();
				url="/kingDee/anchor/violation/info";
				break;
			case "anchorLiveStatusUrl":
				desc = "主播禁播/开播接口";
				url = queryUrlConfig.getAnchorLiveStatusUrl();
				break;
			case "anchorRejectUrl":
				desc = "主播剔除家族接口";
				url = queryUrlConfig.getAnchorRejectUrl();
				break;
			case "anchorOnlineUrl":
				desc = "查询主播是否在线接口";
				url = queryUrlConfig.getAnchorOnlineUrl();
				break;
			case "playerChannelUrl":
				desc = "玩家改绑申请接口";
				url = queryUrlConfig.getPlayerChannelUrl();
				break;
			case "playerAwardQueryUrl":
				desc = "玩家奖励申请查询接口";
				//url = queryUrlConfig.getPlayerAwardQueryUrl();
				url ="/kingDee/user/award/info";
				break;
			case "playerAwardSubmitUrl":
				desc = "玩家奖励申请提交接口";
				url = queryUrlConfig.getPlayerAwardSubmitUrl();
				break;
			case "appInfoUrl":
				desc = "查询产品信息接口";
				url = queryUrlConfig.getAppInfoUrl();
				break;
			case "queryAppVersionByAppIdUrl":
				desc = "根据产品id和子渠道id获取最新版本";
				//url = queryUrlConfig.getQueryAppVersionByAppIdUrl();
				url="/kingDee/app/version";
				break;
			case "queryAnchorInfoByAppIdUrl":
				desc = "根据产品id和业务员id查询对应的主播信息接口";
				//url = queryUrlConfig.getQueryAnchorInfoByAppIdUrl();
				url="/kingDee/anchor/channel/promote";
				break;
			case "queryUnionUrl":
				desc = "根据渠道id查询工会接口";
				url = queryUrlConfig.getQueryUnionUrl();
				break;
			case "queryFocusAnchorUrl":
				desc = "关注主播接口";
				//url = queryUrlConfig.getQueryFocusAnchorUrl();
				url="/kingDee/user/follow/list";
				break;
			case "playerOnlineUrl":
				desc = "查询玩家是否在线接口";
				url = queryUrlConfig.getPlayerOnlineUrl();
				break;

			case "invitationLinkUrl":
				desc = "邀请链接接口";
				//url = queryUrlConfig.getInvitationLinkUrl();
				url="/kingDee/anchor/channel/createInviteLink";
				break;
			default:
				break;
		}
		// 记录日志
		JSONObject synchroLogJsonObj = new JSONObject();
		String id = PrimaryKeyGeneratorUtil.getInstance().getRandomKey();
		synchroLogJsonObj.put("id", id);
		synchroLogJsonObj.put("state", 2);
		synchroLogJsonObj.put("startTime", new Date());
		synchroLogJsonObj.put("desc", desc);
		synchroLogJsonObj.put("name", url);
		synchroLogJsonObj.put("type", 2);
		synchroLogJsonObj.put("createTime", new Date());

		boolean res = false;
		String code = "0";
		String msg = "";
		String data = "";
		String domainUrl = queryUrlConfig == null ? "http://external-test.jiaoyoushow.com" : queryUrlConfig.getDomainUrl();
		if (domainUrl == null || StringUtils.isEmpty(domainUrl)) {
			code = "7002";
			msg = "域名地址为空,请联系管理员";
		} else {
			url = domainUrl + url;
			String timestamp = System.currentTimeMillis() + "";
			String nonce = genReqID();
			String md5Sign="";
			TreeMap paramMap0=new TreeMap();
			if (method.equals("playerChannelUrl")) // 玩家改绑申请接口
			{
				paramMap0.put("timestamp", timestamp);
				paramMap0.put("nonce", nonce);
				md5Sign = getSign(paramMap0, "Asf8811eoE92FFE");
			}
			else
			{
				paramMap.put("timestamp", timestamp);
				paramMap.put("nonce", nonce);
				md5Sign = getSign(paramMap, "Asf8811eoE92FFE");
				paramMap.put("sign", md5Sign);
			}

			if (type == 1) {
				String tempParam = "";
				for (String key : paramMap.keySet()) {
					if (key != null && StringUtils.isNotEmpty(key)) {
						String value = paramMap.get(key) == null ? "" : paramMap.get(key).toString();
						if (StringUtils.isNotEmpty(tempParam)) {
							tempParam = tempParam + "&" + key + "=" + value;
						} else {
							tempParam = tempParam + key + "=" + value;
						}
					}
				}
				if (tempParam != null && StringUtils.isNotEmpty(tempParam)) {
					url = url + "?" + tempParam;
				}

				content = HttpUtil.doGet(url);
				System.out.println("==content=="+content+"==url=="+url+"==paramMap=="+paramMap);
			} else {
				if (method.equals("playerChannelUrl")) {
					url=url+"?timestamp="+timestamp+"&nonce="+nonce+"&sign="+md5Sign;

					JSONObject jsonObject=new JSONObject();
					for (String key : paramMap.keySet()) {
						if (key != null && StringUtils.isNotEmpty(key)) {
							String value = paramMap.get(key) == null ? "" : paramMap.get(key).toString();
							jsonObject.put(key,value);
						}
					}
					content = HttpUtil.doPost(url, jsonObject);
				}
				else
				{
					content = HttpUtil.doPost(url, paramMap);
				}
			}
			if (content != null && StringUtils.isNotEmpty(content)) {
				JSONObject jsonObj = JSON.parseObject(content);
				if (jsonObj != null) {
					if (jsonObj.containsKey("code")) {
						code = jsonObj.getString("code");
						msg = jsonObj.getString("msg");
						data = jsonObj.getString("data");

						// 当返回失败时，需要记录失败的日志记录
						if (!(code != null && StringUtils.isNotEmpty(code) && code.equals("1"))) {

							res = true;
						}
					} else {
						msg = "json对象有误，没有包含状态码";
						res = true;

					}
				} else {
					msg = "转json对象失败";
					res = true;
				}
			} else {
				msg = "返回值为空";
				res = true;
			}
		}
		if (res) {
			System.out.println("==content=="+content+"==url=="+url+"==paramMap=="+paramMap);
			synchroLogJsonObj.put("endTime", new Date());
			synchroLogJsonObj.put("errorLog", msg);

			MongoUtil.getInstance().insert(synchroLogJsonObj, INTERFACE_SYNCHRO_LOG);
		}
		map.put("code",  Integer.parseInt(code));
		map.put("msg", msg);
		map.put("data", data);
		return map;
	}


	public static void main(String[] args) throws Exception{

		// 请求接口
		TreeMap<String, Object> paramMap = new TreeMap<>();
		paramMap.put("loginName", "test2");
		paramMap.put("channelId", "M234212_S234213");
		paramMap.put("anchorId", "110014770");
		Map resultMap =null;// QueryAppUtil.testQuery("invitationLinkUrl", 2, paramMap);

		paramMap = new TreeMap<>();
		paramMap.put("productId", "wasai002");
		paramMap.put("channelId", "M234212_S234213");
		paramMap.put("anchorIds", "110014770");
		//resultMap = QueryAppUtil.testQuery("queryAnchorInfoByAppIdUrl", 1, paramMap);

		paramMap = new TreeMap<>();
		paramMap.put("playId", "110020954");
		paramMap.put("channelId", "M234113_S234114");

		//resultMap = QueryAppUtil.testQuery("playerAwardQueryUrl", 1, paramMap);

		paramMap = new TreeMap<>();

		paramMap.put("family_id", "");
		paramMap.put("pageNum", 1);
		paramMap.put("pageSize", 10);
		paramMap.put("anchorId", "110014770");
		String sendTimeStart ="" ;
		paramMap.put("beginDate", sendTimeStart);
		String sendTimeEnd = "" ;
		paramMap.put("endDate", sendTimeEnd);

		//resultMap = QueryAppUtil.testQuery("anchorViolationInfoUrl", 1, paramMap);

		paramMap = new TreeMap<>();
		paramMap.put("pageNum", 1);
		paramMap.put("pageSize", 10);
		paramMap.put("playerId", "");
		paramMap.put("playerNickName", "");
		paramMap.put("anchorId", "");
		paramMap.put("anchorNickName", "");
		 resultMap = QueryAppUtil.testQuery("queryFocusAnchorUrl", 1, paramMap);


		//String domainUrl = "https://external-pro.jiaoyoushow.com";
		String domainUrl = "http://external-test.jiaoyoushow.com";
		/*String url="/kingDee/family/info";
		url = domainUrl + url;*/

		//改绑
		String url = "/kingDee/user/channel/apply";
		JSONObject jsonObject=new JSONObject();
		/*jsonObject.put("vvId", "110021157");
		jsonObject.put("newScId", "M234233_S234234");
		jsonObject.put("segmentingLine", "2021-8-17 19:00");
		jsonObject.put("recordType", 1);
		jsonObject.put("opType", 1);
		jsonObject.put("tieUpReason", "推广平台同公会改绑改绑");
		jsonObject.put("groupId","25025");
		jsonObject.put("loginName", "test");*/
		//jsonObject.put("imgUrls",new ArrayList());

		String timestamp = System.currentTimeMillis() + "";
		String nonce = genReqID();
		//jsonObject.put("timestamp", timestamp);
		//jsonObject.put("nonce", nonce);


		//TreeMap<String, Object> paramMap=new TreeMap<>();

		/*paramMap.put("vvId", "110021157");
		paramMap.put("newScId", "M234233_S234234");
		paramMap.put("segmentingLine", "2021-8-17 19:00");
		paramMap.put("recordType", 1);
		paramMap.put("opType", 1);
		paramMap.put("tieUpReason", "推广平台同公会改绑改绑");
		paramMap.put("groupId","25025");
		paramMap.put("loginName", "test");*/
		/*paramMap.put("timestamp", timestamp);
		paramMap.put("nonce", nonce);
		String md5Sign = getSign(paramMap,"Asf8811eoE92FFE");
		//jsonObject.put("sign", md5Sign);
		url=url+"?timestamp="+timestamp+"&nonce="+nonce+"&sign="+md5Sign;
		String content = HttpUtil.doPost(domainUrl + url, jsonObject);
		System.out.println("==content==" + content);*/

		//一旦抢单成功，需要向青芒推送业务员和主播的信息，以其生成推广链接
		//TreeMap<String, Object> paramMap = new TreeMap<>();
		/*paramMap.put("anchorId", anchorUserInfo.getOtherAccount());
		paramMap.put("channelId", userInfo.getOtherAccount());
		paramMap.put("loginName", userInfo.getName());
		Map resultMap = QueryAppUtil.query("invitationLinkUrl", 2, paramMap);*/

		/*paramMap.put("familyId", "102638");
		String tempParam = "";

		paramMap.put("timestamp", timestamp);
		paramMap.put("nonce", nonce);
		//md5Sign = getSign(paramMap,"D3F99100FEI211130AF311G3G2");
		paramMap.put("sign", md5Sign);
		for (String key : paramMap.keySet()) {
			if (key != null && StringUtils.isNotEmpty(key)) {
				String value = paramMap.get(key) == null ? "" : paramMap.get(key).toString();
				if (StringUtils.isNotEmpty(tempParam)) {
					tempParam = tempParam + "&" + key + "=" + value;
				} else {
					tempParam = tempParam + key + "=" + value;
				}
			}
		}
		if (tempParam != null && StringUtils.isNotEmpty(tempParam)) {
			url = url + "?" + tempParam;
		}

		//String content = HttpUtil.doGet(url);

		System.out.println("=content==="+content);*/
		/*
		 * //家族 String url1="/kingDee/family/info"; String param="familyId=200214"; //url1=url1+"?"+param; Map map1=new HashMap(); map1.put("familyId","200214"); Map content=null;//query(domainUrl+url1,1,map1); //主播 url1="/kingDee/anchor/info"; param="anchorId=110020915"; //url1=url1+"?"+param; //content=query(domainUrl+url1,1,map1); //推广公会（暂时没有） url1="/kingDee/guild/info"; param="tradeUnionId=110020915";
		 * url1=url1+"?"+param;
		 * 
		 * //查询产品信息 url1="/kingDee/guild/channel/app/info"; param="channelId=M234113_S234114"; url1=url1+"?"+param;
		 * 
		 * //根据产品id和子渠道id获取最新版本接口 url1="/kingDee/anchor/channel/promote"; //param="channelId=M234113_S234114&productId=wasai002"; //url1=url1+"?"+param; map1=new HashMap(); map1.put("channelId","M234113_S234114"); map1.put("productId","wasai002"); content=query(domainUrl+url1,1,map1);
		 * 
		 * //根据产品id获取最新版本接口 url1="/kingDee/app/version"; param="productId=wasai002"; url1=url1+"?"+param;
		 * 
		 * //玩家奖励申请查询接口 url1="/kingDee/user/award/info"; param="playId=110020954&channelId=M234113_S234114"; url1=url1+"?"+param;
		 * 
		 * //String content=query(domainUrl+url1);
		 * 
		 * //玩家奖励申请查询接口 url1="/kingDee/user/award/submit";
		 * 
		 * Map map=new HashMap(); map.put("playId","110020954"); map.put("channelId","M234113_S234114"); map.put("awardType","1"); map.put("awardRule","3"); map.put("awardPrizeId","C15"); map.put("sendVip","true"); //content=doPost(domainUrl+url1,map);
		 * 
		 * System.out.println("==content=="+content);
		 */
	}
}
